<template>
    <div class="upload-container">
        <el-upload
            class="avatar-uploader"
            action="/api/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :headers="headers"
            ref="upload"
        >
            <img v-if="value" :src="imgUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
    </div>
</template>

<script>
import { url } from "@/urlConfig"
export default {
    props: {
        title: { type: String, default: "请上传图片" },
        value: { type: String, default: "" }
    },
    emits: ["input", "delete"],
    computed: {
        imgUrl() {
            if (this.value.startsWith(url)) {
                return this.value
            } else {
                return url + this.value
            }
        },
        headers() {
            return {
                Authorization: "Bearer " + localStorage.getItem("token")
            }
        }
    },
    methods: {
        handleAvatarSuccess(res) {
            if (!res.code && res.data) {
                // 说明上传成功，服务器给我们放回的图片后台地址
                this.$emit("input", res.data)
            }
        }
    }
}
</script>

<style scoped>
.avatar-uploader .el-upload {
    position: relative;
    overflow: hidden;
}
.avatar-uploader-icon:hover {
    border-color: #409eff;
}
.delete-icon:hover {
    color: #409eff;
}
.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    transition: all 0.3s;
}
.avatar {
    width: 178px;
    height: 178px;
    display: block;
    margin: auto;
}
</style>
